package com.craftworks.rtmp;

import com.craftworks.util.BigEndian;

public class RtmpHeader
{
    private int length;
    private int fmt;
    private int csid;
    private int msgLength;
    private int msgTypeID;

//    +--------------+----------------+--------------------+--------------+
//    | Basic Header | Message Header | Extended Timestamp | Chunk Data   |
//    +--------------+----------------+--------------------+--------------+
//    |<------------------- Chunk Header ----------------->|

    public RtmpHeader(byte[] bytes, int offset)
    {
        int b0 = BigEndian.getUINT8(bytes, offset);
        fmt = (b0 >> 6) & 0b11;
        int lb = b0 & 0b111111;
        if (lb == 0)
        {
            length = 3;
            csid = BigEndian.getUINT8(bytes, offset + 1) + 64;
        } else if (lb == 1)
        {
            length = 2;
            csid = BigEndian.getUINT8(bytes, offset + 2) * 256 +
                   BigEndian.getUINT8(bytes, offset + 1) + 64;
        } else
        {
            length = 1;
            csid = lb;
        }

        if (fmt == 0)
        {
            offset += length;
            length += 11;
            msgLength = BigEndian.getUINT24(bytes, offset + 3);
            msgTypeID = BigEndian.getUINT8(bytes, offset + 6);
        }
        if (fmt == 1)
        {
            offset += length;
            length += 7;
            msgLength = BigEndian.getUINT24(bytes, offset + 3);
            msgTypeID = BigEndian.getUINT8(bytes, offset + 6);
        }
        if (fmt == 2)
        {
            length += 3;
            msgTypeID = -1;
        }
    }

    public int getLength()
    {
        return length;
    }

    public int getFormat()
    {
        return fmt;
    }

    public int getChunkStreamID()
    {
        return csid;
    }

    public int getMessageLength()
    {
        return msgLength;
    }

    public int getMessageTypeID()
    {
        return msgTypeID;
    }
}
